package com.dmw.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> valOpsStr;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Resource(name = "redisTemplate")
    private ValueOperations<Object, Object> valOpsObj;

    public boolean exists(String key){

        String value = getString(key);

        if (value == null) return false;

        return true;
    }

    /**
     * 获取失效时间
     * @param key
     * @return
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(key);
    }

    /**
     * 删除键
     * @param key
     */
    public void delete(String key){
        redisTemplate.delete(key);
    }

    /**
     * 设置字符串数据
     * @param key
     * @param val
     */
    public void setString(String key, String val){
        valOpsStr.set(key, val);
    }

    /**
     * 设置字符串数据
     * @param key 键
     * @param val 值
     * @param expire 有效时间
     */
    public void setString(String key, String val, long expire){
        valOpsStr.set(key, val, expire, TimeUnit.SECONDS);
    }

    /**
     * 读取字符串数据
     * @param key
     * @return
     */
    public String getString(String key){
        return valOpsStr.get(key);
    }
}
